//
//  ChangeInfoViewController.m
//  EducationOID
//
//  Created by slz on 2017/8/7.
//  Copyright © 2017年 bnsr. All rights reserved.
//

#import "ChangeInfoViewController.h"
#import "OIPubListViewController.h"
#import "ProgressTextField.h"
#import "BaseHttpTool.h"

typedef void(^ChanegPasswordButtonClickBlock)(NSString * newPwd);


@interface ChangePassWordView : UIView
@property (nonatomic,strong) ProgressTextField *oldPwd;
@property (nonatomic,strong) ProgressTextField *changedPwd;
@property (nonatomic,strong) ProgressTextField *changedPwd1;
@property(nonatomic,copy) ChanegPasswordButtonClickBlock block;


@end

@implementation ChangePassWordView

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.backgroundColor = kChange_InfoColor_bakc_Default;
        [self initViews];
    }
    return self;
}

-(void)initViews{
    _oldPwd = [[ProgressTextField alloc]initWithLeftLabelTitle:@"旧密码:"];
    _oldPwd.keyboardType = UIKeyboardTypeASCIICapable;
    [self addSubview:_oldPwd];
    [_oldPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(11);
        make.trailing.mas_equalTo(-11);
        make.top.mas_equalTo(self.mas_top).offset(11);
        make.height.mas_equalTo(40);
    }];


    _changedPwd = [[ProgressTextField alloc]initWithLeftLabelTitle:@"新密码:"];
    _changedPwd.secureTextEntry = YES;
    _changedPwd.keyboardType = UIKeyboardTypeASCIICapable;
    [self addSubview:_changedPwd];
    [_changedPwd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(11);
        make.trailing.mas_equalTo(-11);
        make.top.mas_equalTo(_oldPwd.mas_bottom).offset(20);
        make.height.mas_equalTo(40);
    }];
    
   
    _changedPwd1 = [[ProgressTextField alloc]initWithLeftLabelTitle:@"确认密码:"];
    _changedPwd1.keyboardType = UIKeyboardTypeASCIICapable;
    _changedPwd1.secureTextEntry = YES;
    [self addSubview:_changedPwd1];
    [_changedPwd1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(11);
        make.trailing.mas_equalTo(-11);
        make.top.mas_equalTo(_changedPwd.mas_bottom).offset(20);
        make.height.mas_equalTo(40);
    }];

    
    UIButton * sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureButton addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    sureButton.titleLabel.fontSize = 15;
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureButton.layer.cornerRadius = 10;
    sureButton.layer.masksToBounds = YES;
    [sureButton setBackgroundColor:[UIColor blackColor]];
    [self addSubview:sureButton];
    [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(60);
        make.right.mas_equalTo(self.mas_right).offset(-60);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(_changedPwd1.mas_bottom).offset(40);
    }];

}

- (void)sureAction{
    if ([MFWStringUtils isEmptyString:_changedPwd.text] || [MFWStringUtils isEmptyString:_changedPwd1.text]){
        [self showTip:@"请输入新密码"];
        return;
    }
    NSString * oldPwd = [[NSUserDefaults standardUserDefaults] stringForKey:kUser_Info_pwd];
    if (![oldPwd isEqualToString:_oldPwd.text]){
        [self showTip:@"密码错误"];
        return;
    }
    if (![_changedPwd.text isEqualToString:_changedPwd1.text]){
        [self showTip:@"新密码不一致"];
        return;
    }
    if (_block){
        _block(_changedPwd1.text);
    }
}

@end


@interface ChangeInfoViewController ()
@property (nonatomic,strong) ProgressTextField *field1;
@property (nonatomic,strong) ProgressTextField *filed2;
@property (nonatomic,strong) ChangePassWordView *passWordView;
@property(nonatomic,assign) BOOL state; //修改密码页面出现状态

@end

@implementation ChangeInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.showNavigationBar = YES;
    [self setControllerTitle:@"个人信息修改"];
    self.view.backgroundColor = kChange_InfoColor_bakc_Default;
    
    UIBarButtonItem * item = [UIBarButtonItem itemWithImage:@"top_back_1" selectImage:nil addTarget:self andAction:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = item;
    [self initViews];
    _passWordView = [self passWordView];
    // Do any additional setup after loading the view.
}

-(ChangePassWordView *)passWordView{
    if (_passWordView == nil){
        _passWordView = [[ChangePassWordView alloc]initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight - 204)];
        @weakify(self);
        _passWordView.block = ^(NSString *newPwd){
            @strongify(self);
            [self changePwdRequestWithNewpwd:newPwd];
        };
        [self.view addSubview:_passWordView];
    }
    return _passWordView;
}

- (void)changePwdRequestWithNewpwd:(NSString *)newpwd{
    MFWUserInfo * user = [MFWSdkEnvironment sharedInstance].userInfo;
    @weakify(self);
    [BaseHttpTool get:kAPI_OID_CHANGE_USERPWD params:@{@"id":user.uid,@"newpassword":newpwd} success:^(id responseObj) {
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        @strongify(self);
        [self showInfoWithJson:json];
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];

}

- (void)initViews{
    PubListTableHeadView * headerView = [[PubListTableHeadView alloc]init];
    headerView.titleLabel.text = @"用户信息修改";
    [self.view addSubview:headerView];
    [headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.view.mas_top);
        make.height.mas_equalTo(80);
    }];
    
    _field1 = [[ProgressTextField alloc]initWithLeftLabelTitle:@"用户名:"];
    _field1.keyboardType = UIKeyboardTypeASCIICapable;
    [self.view addSubview:_field1];
    [_field1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(11);
        make.trailing.mas_equalTo(-11);
        make.top.mas_equalTo(headerView.mas_bottom).offset(11);
        make.height.mas_equalTo(40);
    }];
    
    
    _filed2 = [[ProgressTextField alloc]initWithLeftLabelTitle:@"邮   箱:"];
    _filed2.keyboardType = UIKeyboardTypeASCIICapable;
    [self.view addSubview:_filed2];
    [_filed2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(11);
        make.trailing.mas_equalTo(-11);
        make.top.mas_equalTo(_field1.mas_bottom).offset(20);
        make.height.mas_equalTo(40);
    }];

    
    UIButton * sureButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sureButton addTarget:self action:@selector(sureAction) forControlEvents:UIControlEventTouchUpInside];
    [sureButton setTitle:@"确定" forState:UIControlStateNormal];
    sureButton.titleLabel.fontSize = 15;
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureButton.layer.cornerRadius = 10;
    sureButton.layer.masksToBounds = YES;
    [sureButton setBackgroundColor:[UIColor blackColor]];
    [self.view addSubview:sureButton];
    [sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(60);
        make.right.mas_equalTo(self.view.mas_right).offset(-60);
        make.height.mas_equalTo(40);
        make.top.mas_equalTo(_filed2.mas_bottom).offset(40);
    }];
    
    UIButton * changePwdButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [changePwdButton addTarget:self action:@selector(changePwdAction:) forControlEvents:UIControlEventTouchUpInside];
    [changePwdButton setTitle:@"修改密码" forState:UIControlStateNormal];
    changePwdButton.titleLabel.fontSize = 15;
    [changePwdButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [changePwdButton setBackgroundColor:kBack_Color_Default];
    [self.view addSubview:changePwdButton];
    [changePwdButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).offset(60);
        make.right.mas_equalTo(self.view.mas_right).offset(-60);
        make.height.mas_equalTo(40);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-10);
    }];
}

#pragma mark - action

- (void)changePwdAction:(UIButton*)button{
    _state = !_state;
    [button setTitle:_state ? @"修改信息" : @"修改密码" forState:UIControlStateNormal];
    
    [UIView animateWithDuration:.5 animations:^{
        _passWordView.top = _state ? 80 : kScreenHeight;
    }];
    
}

-(void)sureAction{
    BOOL isEmail = [self validateEmail:_filed2.text];
    if (!isEmail){
        [self.view showTip:@"请输入正确的邮箱"];
        return;
    }
    if ([MFWStringUtils isEmptyString:_field1.text])
    {
        [self.view showTip:@"请输入用户名"];
        return;
    }
    MFWUserInfo * user = [MFWSdkEnvironment sharedInstance].userInfo;
    @weakify(self);
    [BaseHttpTool get:kAPI_OID_CHANGE_USERINFO params:@{@"id":user.uid,@"username":_field1.text,@"email":_filed2.text} success:^(id responseObj) {
        MFWJson * json = [MFWJson jsonWithObject:responseObj];
        @strongify(self);
        [self showInfoWithJson:json];
    } failure:^(NSError *error) {
        [self.view showTip:error.localizedDescription];
    }];

}

-(void)showInfoWithJson:(MFWJson *)json{
    BOOL success = [json booleanValueForKey:@"parameter"];
    NSString * feedback =[json stringValueForKey:@"data"];
    if (!success)
    {
        [self.view showTip:feedback];
    }else
    {
        [self.view showTip:@"修改成功" completion:^{
            // todo 返回前页 可能需要退出登录
        }];
        
    }
}

- (BOOL)validateEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
